<template>
  <div class="topTool">
    <el-input v-model="aname" placeholder="请输入活动名称搜索" @input="handleSearchName" :prefix-icon="Search">
    </el-input>
    <el-button type="primary" :icon="Plus" @click="handleAdd" style="margin-left: 20px;">添加活动</el-button>
  </div>
  
  <el-table :data="tableData" stripe style="width: 100%" @sort-change="handleSortChange">
    <el-table-column prop="aid" label="活动ID" width="100" sortable />
    <el-table-column prop="aname" label="活动名称" width="150" />
    <el-table-column prop="des" label="活动介绍" width="200" />
    <el-table-column prop="people" label="人数上限" width="100" />
    <el-table-column prop="adress" label="活动地点" width="150" />
    <el-table-column prop="oid" label="组织者ID" width="100" />
    <el-table-column prop="reg_start" label="报名开始时间" width="180" />
    <el-table-column prop="reg_end" label="报名截止时间" width="180" />
    <el-table-column prop="act_start" label="活动开始时间" width="180" />
    <el-table-column prop="act_end" label="活动结束时间" width="180" />
    <el-table-column prop="state" label="审核状态" width="120">
      <template #default="{ row }">
        <el-tag :type="getStateTagType(row.state)">
          {{ getStateText(row.state) }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="password" label="签到码" width="120" />
    <el-table-column label="操作" min-width="180">
      <template #default="{ row }">
        <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
        <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑活动' : '添加活动'" width="600px">
    <el-form :model="formData" label-width="100px">
      <el-form-item label="活动名称">
        <el-input v-model="formData.aname" />
      </el-form-item>
      <el-form-item label="活动介绍">
        <el-input v-model="formData.des" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item label="人数上限">
        <el-input-number v-model="formData.people" :min="1" />
      </el-form-item>
      <el-form-item label="活动地点">
        <el-input v-model="formData.adress" />
      </el-form-item>
      <el-form-item label="组织者ID">
        <el-input v-model="formData.oid" />
      </el-form-item>
      <el-form-item label="报名开始时间">
        <el-date-picker
          v-model="formData.reg_start"
          type="datetime"
          placeholder="选择日期时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="报名截止时间">
        <el-date-picker
          v-model="formData.reg_end"
          type="datetime"
          placeholder="选择日期时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="活动开始时间">
        <el-date-picker
          v-model="formData.act_start"
          type="datetime"
          placeholder="选择日期时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="活动结束时间">
        <el-date-picker
          v-model="formData.act_end"
          type="datetime"
          placeholder="选择日期时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="审核状态">
  <el-tag :type="getStateTagType(formData.state)">
    {{ getStateText(formData.state) }}
  </el-tag>
</el-form-item>
      <el-form-item label="签到码">
        <el-input v-model="formData.password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { Plus, Delete, Edit, Search } from '@element-plus/icons-vue'
import axios from 'axios'
axios.defaults.withCredentials = true;
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from "element-plus";

const formData = reactive({
  aid: null,
  aname: '',
  des: '',
  people: 50,
  adress: '',
  oid: '',
  reg_start: '',
  reg_end: '',
  act_start: '',
  act_end: '',
  state: 0, // 默认待审核(0)
  password: ''
})

const dialogVisible = ref(false)
const isEdit = ref(false)
const tableData = ref([])
const aname = ref('')

// 获取活动数据
const fetchActivities = async () => {
  const token = localStorage.getItem('authToken');
  const response = await axios.get("http://localhost:8080/actions", {
    headers: { Authorization: `Bearer ${token}` }
  });
  tableData.value = response.data;
};

// 排序处理
const handleSortChange = (sortData: { prop: string; order: 'ascending' | 'descending' | null }) => {
  const { prop, order } = sortData;
  if (!order || !prop) return;

  tableData.value = tableData.value.sort((a, b) => {
    if (order === 'ascending') {
      return a[prop] > b[prop] ? 1 : -1;
    } else {
      return a[prop] < b[prop] ? 1 : -1;
    }
  });
};

// 按名称搜索
const handleSearchName = (val: string) => {
  if(val.length > 0) {
    axios.get(`http://localhost:8080/activityByName/${val}`).then(response => {
      tableData.value = response.data
    }).catch(error => {
      console.error(error)
    })
  } else {
    fetchActivities();
  }
}

// 状态标签类型
const getStateTagType = (state: number) => {
  switch(state) {
    case 2: return 'success'; // 已通过
    case 3: return 'danger';  // 已拒绝
    case 1: return 'info';    // 审核中
    default: return 'warning'; // 待审核
  }
}

// 状态数字转文本
const getStateText = (state: number) => {
  switch(state) {
    case 0: return '待审核';
    case 1: return '审核中';
    case 2: return '已通过';
    case 3: return '已拒绝';
    default: return '未知状态';
  }
}

// 添加活动
const handleAdd = () => {
  isEdit.value = false;
  Object.assign(formData, {
    aid: null,
    aname: '',
    des: '',
    people: 50,
    adress: '',
    oid: '',
    reg_start: '',
    reg_end: '',
    act_start: '',
    act_end: '',
    state: 0, // 默认待审核
    password: ''
  });
  dialogVisible.value = true;
};

// 编辑活动
const handleEdit = (row: any) => {
  isEdit.value = true;
  Object.assign(formData, {
    ...row, // 确保所有字段（包括 state）从 row 复制到 formData
  });
  dialogVisible.value = true;
};


// 保存活动
const handleSave = async () => {
  try {
    const token = localStorage.getItem('authToken');
    if (!token) throw new Error("未找到 token");

    if (isEdit.value) {
      // 修改活动
      await axios.put(`http://localhost:8080/activities`, formData, {
        headers: { Authorization: `Bearer ${token}` }
      });
      ElMessage.success("修改成功");
    } else {
      // 添加活动
      await axios.post(`http://localhost:8080/actions`, formData, {
        headers: { Authorization: `Bearer ${token}` }
      });
      ElMessage.success("添加成功");
    }
    dialogVisible.value = false;
    fetchActivities();
  } catch (err) {
    console.error(err);
    ElMessage.error("操作失败");
  }
};

// 删除活动
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定删除活动 "${row.aname}" 吗？`,
    '提示',
    {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }
  ).then(async () => {
    const token = localStorage.getItem('authToken');
    await axios.delete(`http://localhost:8080/activities/${row.aid}`, {
      headers: { Authorization: `Bearer ${token}` }
    });
    ElMessage.success("删除成功");
    fetchActivities();
  }).catch(() => {
    ElMessage.info("取消删除");
  });
};

// 组件挂载时获取数据
onMounted(() => {
  fetchActivities();
});
</script>

<style scoped>
.topTool {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}
</style>